package csu.web.credit_bank.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import csu.web.credit_bank.mapper.UserResourceMapper;
import csu.web.credit_bank.pojo.Students;
import csu.web.credit_bank.pojo.Teachers;
import csu.web.credit_bank.pojo.User;
import csu.web.credit_bank.pojo.UserResource;
import csu.web.credit_bank.pojo.vo.ResourceVO;
import csu.web.credit_bank.service.StudentsService;
import csu.web.credit_bank.service.TeachersService;
import csu.web.credit_bank.service.UserResourceService;
import csu.web.credit_bank.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserResourceServiceImpl extends ServiceImpl<UserResourceMapper, UserResource> implements UserResourceService {


    @Autowired
    private UsersService usersService; // 注入 UsersService
    @Autowired
    private StudentsService studentsService; // 注入 StudentsService
    @Autowired
    private TeachersService teachersService; // 注入 TeachersService
    @Override
    @Transactional // 开启事务，保证操作的原子性
    public void joinResource(String userId, String resourceId) {
        // 1. 检查是否已经加入过
        QueryWrapper<UserResource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("resource_id", resourceId);

        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new IllegalStateException("您已经加入过该资源，请勿重复加入");
        }

        // 2. 创建新的关联记录
        UserResource userResource = new UserResource();
        userResource.setUserId(userId);
        userResource.setResourceId(resourceId);

        boolean success = this.save(userResource);
        if (!success) {
            throw new RuntimeException("加入资源失败，请稍后再试");
        }
    }

    @Override
    public IPage<ResourceVO> getJoinedResources(String userId, Page<ResourceVO> page) {
        // 调用我们刚刚在Mapper中定义的自定义查询方法
        IPage<ResourceVO> resultPage = baseMapper.findJoinedResourcesByUserId(page, userId);

        // 【新增：填充 publisherAvatar 逻辑】
        if (resultPage != null && resultPage.getRecords() != null && !resultPage.getRecords().isEmpty()) {
            Set<String> publisherIds = resultPage.getRecords().stream()
                    .map(ResourceVO::getPublisherId)
                    .filter(StringUtils::hasText)
                    .collect(Collectors.toSet());

            if (!publisherIds.isEmpty()) {
                List<User> users = usersService.listByIds(publisherIds);
                Map<String, User> userMap = users.stream()
                        .collect(Collectors.toMap(User::getId, user -> user));

                Set<String> studentIds = new HashSet<>();
                Set<String> teacherIds = new HashSet<>();
                for (String pId : publisherIds) {
                    User user = userMap.get(pId);
                    if (user != null && user.getUserType() != null) {
                        if (user.getUserType() == 0) { // 假设 0 是学生
                            studentIds.add(pId);
                        } else if (user.getUserType() == 1) { // 假设 1 是教师
                            teacherIds.add(pId);
                        }
                    }
                }

                Map<String, String> avatarMap = new HashMap<>();
                if (!studentIds.isEmpty()) {
                    List<Students> students = studentsService.listByIds(studentIds);
                    students.forEach(s -> avatarMap.put(s.getUserId(), s.getAvatar()));
                }
                if (!teacherIds.isEmpty()) {
                    List<Teachers> teachers = teachersService.listByIds(teacherIds);
                    teachers.forEach(t -> avatarMap.put(t.getUserId(), t.getAvatar()));
                }

                for (ResourceVO resourceVO : resultPage.getRecords()) {
                    String publisherId = resourceVO.getPublisherId();
                    if (StringUtils.hasText(publisherId) && avatarMap.containsKey(publisherId)) {
                        resourceVO.setPublisherAvatar(avatarMap.get(publisherId));
                    }
                }
            }
        }
        return resultPage;
    }

    @Override
    public Set<String> getOwnedResourceIds(String userId, List<String> resourceIds) {
        if (resourceIds == null || resourceIds.isEmpty()) {
            return new HashSet<>();
        }
        QueryWrapper<UserResource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.in("resource_id", resourceIds);

        List<UserResource> userResources = this.list(queryWrapper);

        return userResources.stream()
                .map(UserResource::getResourceId)
                .collect(Collectors.toSet());
    }
}